﻿using Net.Share;
using Net.System;
using System;
using System.Runtime.InteropServices;
using Udx;

namespace Net.Server
{
    /// <summary>
    /// udx客户端对象
    /// </summary>
    public class UdxPlayer : ClientPeerBase
    {
        public IntPtr Udx { get; set; }
        public GCHandle Handle;

        public override void ReceiveHandler()
        {
            while (ReceiveList.TryDequeue(out var segment))
            {
                ReceiveHandler(ref segment);
                BufferPool.Push(segment);
            }
        }

        protected override bool CheckIsConnected()
        {
            if (!Connected)
            {
                if (Environment.TickCount >= ReconnectTimeout)
                    RemoveClient();
                return false;
            }
            return true;
        }

        protected unsafe override void SendByteData(ISegment buffer)
        {
            if (Udx == IntPtr.Zero)
                return;
            trafficStatistics.SentPacketsPerSecond++;
            trafficStatistics.SentBytesPerSecond += buffer.Count;
            fixed (byte* ptr = buffer.Buffer)
            {
                int count = UdxLib.USend(Udx, ptr, buffer.Count);
                if (count <= 0)
                    OnSendErrorHandle?.Invoke(buffer);
            }
        }

        public override void Dispose()
        {
            if (IsDispose)
                return;
            base.Dispose();
            if (Handle.IsAllocated)
                Handle.Free();
        }
    }
}
